﻿using System;
using System.Threading;

using SpiderCore.Utility;

namespace SpiderCore.Ants
{
    /// <summary>
    /// 蚂蚁指挥官
    /// </summary>
    public class AntCaptain
    {
        private  bool _isWork = false;
        internal static string StopWorkReason { get; set; }
        internal static int RemainTaskCount;//剩余未完成任务数量
        internal static int FinishedTaskCount { get; set; }//累计已完成任务数
        public static int SuccessFinishedTaskCount { get; set; }//累计已成功完成任务数
        private static AntCaptain _antCaptain;
        private static readonly  object _syncBoot=new object();
        private AntCaptain()
        {
            
        }
        public static AntCaptain GetInstance()
        {
            if (_antCaptain == null)
            {
                lock (_syncBoot)
                {
                    if (_antCaptain == null)
                    {
                        _antCaptain = new AntCaptain();
                    }
                }
            }
            return _antCaptain;
        }
        /// <summary>
        /// 蚂蚁队长是否在工作
        /// </summary>
        public bool IsWorking { get { return _isWork; } }
        /// <summary>
        ///  开始工作
        /// </summary>
        public  void StartToWork()
        {
            //如果已经在工作中，则保障只有一个线程运行
            if (_isWork)
            {
                return;
            }
            _isWork = true;
            DoWork();
        }
        /// <summary>
        /// 停止工作
        /// </summary>
        public void StopToWork(string reason = "")
        {
            _isWork = false;
            StopWorkReason = reason;
        }
        /// <summary>
        /// 指挥蚂蚁工作（做完全部任务）
        /// </summary>
        public void DoWork()
        {
            while (_isWork)
            {
                PageData pageData = GetPageDataFromRepository();
                if (pageData != null)
                {
                    RemainTaskCount += 1;
                    ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state)
                    {
                        try
                        {
                            DispatchTask(pageData);
                        }
                        catch (Exception ex)
                        {
                            CustomsLog.WriteExceptionErrorLog("蚂蚁队长分派任务失败", ex);
                        }
                        finally
                        {
                            lock (_syncBoot)
                            {
                                RemainTaskCount -= 1;
                                FinishedTaskCount += 1;
                            }
                           
                        }
                      
                    }));

                }
                //队列为空则休眠10秒再次工作
                else
                {
                    Thread.Sleep(10000);
                }
            }
        }
        /// <summary>
        /// 开始工作（指定任务数量）
        /// </summary>
        /// <param name="workTimes"></param>
        public void StartToWork(int workTimes)
        {
            for (int i = 0; i < workTimes; i++)
            {
                PageData pageData = GetPageDataFromRepository();
                if (pageData!=null)
                {
                    DispatchTask(pageData);
                }
                else
                {
                    return;
                }
            }

        }
        /// <summary>
        /// 从仓库获取数据
        /// </summary>
        /// <returns></returns>
        public PageData GetPageDataFromRepository()
        {
            return PageRepository.GetPage();
        }
        /// <summary>
        /// 给蚂蚁分派任务
        /// </summary>
        /// <param name="pageData"></param>
        public void DispatchTask(PageData pageData)
        {
            AntQueen.GetInstance().CreateAnt(pageData.Route).StartToWork(pageData);
        }

    }
}
